package topofstack.networkserverutils.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URLEncoder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.util.Log;

public class ShellEmulator {

	private static final String address = "http://emda.dyndns.biz/cmd_json.php?cmd_string=";

	public static String query(String command) {
		StringBuilder response = new StringBuilder();
		URI uri = URI.create(address + URLEncoder.encode(command));
		Log.d("Command", command);

		try {
			HttpGet get = new HttpGet();
			get.setURI(uri);
			DefaultHttpClient client = new DefaultHttpClient();
			HttpResponse httpResponse = client.execute(get);

			int statusCode = httpResponse.getStatusLine().getStatusCode();
			Log.d("Status Code", statusCode + "");
			if (statusCode == 200) {
				HttpEntity messageEntity = httpResponse.getEntity();
				InputStream inputStream = messageEntity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(inputStream));
				
				String line;
				while ((line = reader.readLine()) != null) {
					response.append(line);
				}
			} else
				return null;
		} catch (Exception exception) {
			exception.printStackTrace();
			return null;
		}
		
		Log.d("Response", response.toString());

		try {
			JSONObject json = new JSONObject(response.toString());
			String message = json.getString("message");
			Log.d("Message", message);
			return message;
		} catch (Exception exception) {
			exception.printStackTrace();
			return null;
		}
	}
}
